#!/bin/bash
### BEGIN INIT INFO
# Provides:             fdevmgr
# Required-Start:       $syslog $remote_fs
# Required-Stop:        $syslog $remote_fs
# Should-Start:         $local_fs
# Should-Stop:          $local_fs
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    fdevmgr service
# Description:          fdevmgr service
### END INIT INFO
# 启动 fdevmgr 服务
# 在 service 管理系统服务的平台要修改service_user和service_folder
# 在 systemctl 管理系统服务的平台,不要直接使用此脚本控制服务启动，
# 应该创建 /etc/systemd/system/fdevmgr.service,在 fdevmgr.service 中调用此脚本，此脚本不需要修改

# 指定运行脚本的帐户名,用于 service 管理系统服务时要修改此变量为指定启动的服务的帐户
service_user=$(whoami)
# 指定服务工作文件夹,用于 service 管理系统服务时要修改此变量为固定常量
service_folder=$(dirname $(readlink -f $0))
# 指定运行脚本日志输出文件
service_out='fdevmgr.out'
# 属性名常量
DB_URL='spring.datasource.url'
DB_DBNAME='spring.datasource.username'
DB_DBPWD='spring.datasource.password'
SERVER_PORT='server.port'
REDIS_HOST='spring.redis.host'
REDIS_PORT='spring.redis.port'
REDIS_PWD='spring.redis.password'
REDIS_DATABASE='spring.redis.database'
FACELOG_HOST='fdevmgr.facelog.host'
FACELOG_PORT='fdevmgr.facelog.port'
FACELOG_ROOTPWD='fdevmgr.facelog.rootpwd'
DOWNLOAD_PREFIX='fdevmgr.properties.downloadpreffix'
FILE_PATH='fdevmgr.properties.filepath'
# 所有需要加入服务参数的属性
ALL_PROPS=( $FACELOG_HOST $FACELOG_PORT $FACELOG_ROOTPWD $DOWNLOAD_PREFIX $DB_DBNAME $DB_DBPWD $DB_URL $SERVER_PORT $REDIS_HOST $REDIS_PORT $REDIS_PWD $REDIS_DATABASE $FILE_PATH)

[ "$service_user" != "$(whoami)" ] && [ "$(whoami)" != 'root' ] && echo "必须在 $service_user 或 root 用户下执行" && exit 255

config="/home/$service_user/.facelog/fdevmgr.properties"
function prop {
	[ -f "$config" ] && grep -P "^\s*[^#]?${1}=.*$" $config | cut -d'=' -f2
}
## 读取properties中的参数，并创建参数名命名的变量，如果参数名中包含'.'则替换为'-'
if [ -f "$config" ]
then
	#echo "load property from $config"
	while IFS='=' read -r key value || [ -n "$key" ]
	do	
		[ -z "$key" ] && continue
		# '.'替换为'-'
		key=$(echo $key | tr '.' '_')
		## 不处理＃起始的key
		[[ -z $(echo "$key" | grep -E '\s*#+.*' ) ]] \
			&& eval "${key}='${value}'"
	done < "$config"
else
	echo "$config not found."
fi

server_port=$spring_server_port

[ -z "$server_port" ] && server_port=8088

# 从.分隔的property名转为_分隔的变量名并获取变量值
# $1 .分隔的property名字符串,such as server.port
function value_of_prop(){ 
	local n=${1//./_}
	echo ${!n}
}

# 返回 fdemgr 的 PID
function fdevmgr_pid(){
	ps -ef | grep -v grep | grep -E "java\s+.*-jar\s+\S*fdevmgr-server-\S+" | awk '{print $2}'
}
# 判断指定的PID 占用的端口是否为$server_port,是返回0,否则返回-1
# $1 进程ID
function is_server_port(){
	netstat -nlp 2>/dev/null | grep "$1" | grep :$server_port 
}
## 停止 fdevmgr
function stop(){
	local pid=$(fdevmgr_pid)
	if [ -n "$pid" ] 
	then	
		kill -9 $pid || exit 255 
		echo "fdevmgr $pid killed"
	fi
	return 0
}
## 启动 fdevmgr
function start(){

	local pid=$(fdevmgr_pid)
	if [ -n "$pid" ] 
	then
		is_server_port $pid && echo "服务已上线" && return 0
	else	
		nc -w 1 localhost $server_port 2>/dev/null && echo "ERROR:服务端口被占用(fdevmgr port $server_port occupied by other process)" && return 255
	fi
	# 设置 HOME 位置	
	[ "$service_user" != "$(whoami)" ] && export FACELOG_OPTS="-Duser.home=/home/$service_user"
	# 设置 java 搜索路径
	[ -n "$java_exe" ] && [ "$(which java 2>/dev/null)" != "$java_exe"] && export PATH="$java_exe":$PATH
	# 是否挂起
	local no_hang_up=0;
	# 是否输出重定向
	local redirect=" > $service_out 2>&1";
	# 解析输入参数
	while [ $# -ge 1 ] ; do
		case "$1" in
			-u|--hup) no_hang_up=1; shift 1;;
			-s|--stdout) redirect='' ; shift 1;;
			*) echo "无效参数 $1." ; exit 255;;
		esac
	done
	echo "启动 fdevmgr 服务(start fdevmgr service)..."
	[ -n "$redirect" ] && echo "执行 tail -f $service_folder/fdevmgr.out 查看控制台输出"

	local run_cmd="./fdevmgrWhse/target/start_fdevmgr_server.sh "
	# 将属性值定义加入命令行参数
	for name in ${ALL_PROPS[@]}
	do	
		local v="$(value_of_prop $name)"		
		if [ -n "$v" ]
		then
			v=${v//&/\\&}
			echo "$name=$v"
			run_cmd="$run_cmd --$name=$v"		
		fi
	done
	echo run_cmd=$run_cmd
	if [ $no_hang_up -eq 0 ] 
	then		
		if [ "$service_user" != "$(whoami)" ]
		then
			su -c "cd $service_folder; nohup $run_cmd $redirect &" - "$service_user"
		else
			eval nohup $run_cmd $redirect &
		fi
	else
		# --hup 用于 systemctl 控制
		eval $run_cmd $redirect
	fi
}

## 显示 fdevmgr 服务状态
function status(){
	# 当前运行的 fdevmgr PID
	local pid=$(fdevmgr_pid)
	# 检测 fdevmgr 是否正常运行
	[ -n "$pid" ] && echo "fdevmgr    [ON] PID $pid PORT $server_port " && return 0
	echo "fdevmgr    [OFF]"
	return 1
}
pushd $service_folder > /dev/null 2>&1
case $1 in
	start)
		shift 1;
		start $*
		exit 0
		;;
	stop)
		stop
		exit 0
		;;
	status)
		status				
		exit 0
		;;
	restart|force-reload)
		stop
		start
		exit 0
		;;
	*)
		echo "Usage: /etc/init.d/fdevmgr {start|stop|restart|force-reload|status}"
		exit 1
		;;
esac
popd > /dev/null 2>&1
